package com.zhangc.zcscm.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhangc.zcscm.client.SCMConstant;
import com.zhangc.zcscm.client.SCMException;

public class ParamUtil {
    public static final String DOCKER_CACHE_FILE_PATH = "/opt/files/componentCacheProperties.conf";
    public static final String DOCKER_CACHE_FILE_KEY = "cachePath";
    private static Logger logger = LoggerFactory.getLogger(ParamUtil.class);
    public static final String PATH_SEPARATOR = "/";
    public static final String SCM = "scm";
    public static ConcurrentHashMap<String, String> paths = new ConcurrentHashMap();
    private static final Set<Class> BASEDATATYPE = new HashSet<Class>() {
        {
            this.add(Short.TYPE);
            this.add(Integer.TYPE);
            this.add(Long.TYPE);
            this.add(Float.TYPE);
            this.add(Double.TYPE);
            this.add(Boolean.TYPE);
            this.add(Character.TYPE);
            this.add(Short.class);
            this.add(Integer.class);
            this.add(Long.class);
            this.add(Float.class);
            this.add(Double.class);
            this.add(Boolean.class);
            this.add(Character.class);
            this.add(String.class);
        }
    };

    public ParamUtil() {
    }

    public static String getParamFromMap(Map<String, Object> map) {
        if (map == null) {
            throw new IllegalArgumentException("map is null!");
        } else {
            List<Entry<String, Object>> mappingList = new ArrayList(map.entrySet());
            Collections.sort(mappingList, new Comparator<Entry<String, Object>>() {
                public int compare(Entry<String, Object> entry1, Entry<String, Object> entry2) {
                    return ((String) entry1.getKey()).compareTo((String) entry2.getKey());
                }
            });
            StringBuilder builder = new StringBuilder();
            Iterator i$ = mappingList.iterator();

            while (true) {
                while (i$.hasNext()) {
                    Entry<String, Object> entry = (Entry) i$.next();
                    Object obj = entry.getValue();
                    if (BASEDATATYPE.contains(obj.getClass())) {
                        builder.append((String) entry.getKey()).append("=").append(obj).append("&");
                    } else if (obj.getClass().isArray()) {
                        int arrLength = Array.getLength(obj);
                        if (arrLength > 0) {
                            for (int i = 0; i < arrLength; ++i) {
                                builder.append((String) entry.getKey()).append("=").append(Array.get(obj, i)).append("&");
                            }
                        }
                    } else {
                        if (!(obj instanceof Collection)) {
                            throw new RuntimeException("Can't parse complex Object:" + obj.getClass());
                        }

                        Collection collection = (Collection) obj;
                        if (collection.size() > 0) {
                            Iterator i$1 = collection.iterator();

                            while (i$1.hasNext()) {
                                Object o = i$1.next();
                                builder.append((String) entry.getKey()).append("=").append(o).append("&");
                            }
                        }
                    }
                }

                builder.deleteCharAt(builder.lastIndexOf("&"));
                return builder.toString();
            }
        }
    }

    public static String getEncodedParamFromMap(Map<String, Object> map) throws UnsupportedEncodingException {
        if (map == null) {
            throw new IllegalArgumentException("map is null!");
        } else {
            Map<String, Object> encodedMap = new HashMap();
            Iterator i$ = map.entrySet().iterator();

            while (true) {
                while (i$.hasNext()) {
                    Entry<String, Object> entry = (Entry) i$.next();
                    Object obj = entry.getValue();
                    if (obj instanceof String) {
                        encodedMap.put(entry.getKey(), URLEncoder.encode((String) obj, "UTF-8"));
                    } else if (obj.getClass().isArray()) {
                        int arrLength = Array.getLength(obj);
                        Object[] arr = new Object[arrLength];

                        for (int i = 0; i < arrLength; ++i) {
                            if (Array.get(obj, i) instanceof String) {
                                arr[i] = URLEncoder.encode((String) Array.get(obj, i), "UTF-8");
                            } else {
                                arr[i] = Array.get(obj, i);
                            }
                        }

                        encodedMap.put(entry.getKey(), arr);
                    } else if (!(obj instanceof Collection)) {
                        encodedMap.put(entry.getKey(), obj);
                    } else {
                        Collection collection = (Collection) obj;
                        int arrLength = collection.size();
                        Object[] arr = new Object[arrLength];
                        int i = 0;

                        for (Iterator i$1 = collection.iterator(); i$1.hasNext(); ++i) {
                            Object o = i$1.next();
                            if (o instanceof String) {
                                arr[i] = URLEncoder.encode((String) o, "UTF-8");
                            } else {
                                arr[i] = o;
                            }
                        }

                        encodedMap.put(entry.getKey(), arr);
                    }
                }

                return getParamFromMap(encodedMap);
            }
        }
    }

    public static String getCachePath() {
        String filePath = SCMConstant.FILE_PATH;
        if (!StringUtils.isEmpty((String) paths.get("cachePath"))) {
            return (String) paths.get("cachePath");
        } else {
            File file = new File("/opt/files/componentCacheProperties.conf");
            if (!file.exists()) {
                return filePath;
            } else {
                FileInputStream in = null;
                Properties properties = new Properties();

                try {
                    in = new FileInputStream(file);
                    properties.load(in);
                } catch (IOException var13) {
                    logger.error("Exception when getCachePath properties load error.", var13);
                } finally {
                    try {
                        in.close();
                    } catch (IOException var12) {
                        logger.error("close stream error", var12);
                    }

                }

                String dockerFilePath = properties.getProperty("cachePath");
                if (!StringUtils.isEmpty(dockerFilePath)) {
                    if (dockerFilePath.endsWith("/")) {
                        dockerFilePath = dockerFilePath.substring(0, dockerFilePath.length() - 1);
                    }

                    filePath = dockerFilePath + "/" + "scm";
                    File f = new File(filePath);
                    if (!f.exists() && !f.mkdirs()) {
                        throw new SCMException("Failed to create dockerCachePath, Check permissions.");
                    }

                    paths.put("cachePath", filePath);
                }

                return filePath;
            }
        }
    }
}
